package cn.xchat.server.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@ServerEndpoint("/server/{name}")
@Component
public class WebScoketServer {

    private static Logger logger= LoggerFactory.getLogger(WebScoketServer.class);

    private static CopyOnWriteArraySet<WebScoketServer> connectSet=new CopyOnWriteArraySet<>();

    private Session session;

    private String name;

    @OnOpen
    public void onOpen(Session session, @PathParam("name") String name){
        this.session=session;
        this.name=name;
        connectSet.add(this);
        try {
            this.sendMessage("连接成功");
            logger.info("连接数："+connectSet.size());
        } catch (IOException e) {
            connectSet.remove(this);
        }
    }

    @OnClose
    public void onClose(){
        connectSet.remove(this);
    }

    @OnMessage
    public void onMessage(String message){
        connectSet.forEach(item->{
            try{
                item.sendMessage(message);
            }catch (IOException e){
                connectSet.remove(this);
            }
        });
    }

    @OnError
    public void onError(Throwable error){
        connectSet.remove(this);
    }

    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
}
